<template>
  <div class="message-query">
    <!-- 查询表单 -->
    <el-form :model="queryForm" :inline="true" class="query-form">
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryForm.userName"
          placeholder="请输入用户名查询"
          clearable
          style="width: 150px"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryForm.userId"
          placeholder="请输入用户ID查询"
          clearable
          style="width: 150px"
        ></el-input>
      </el-form-item>
      <el-form-item label="在线状态" prop="online">
        <el-select
          v-model="queryForm.online"
          placeholder="请选择"
          clearable
          style="width: 120px"
        >
          <el-option label="在线" :value="true"></el-option>
          <el-option label="离线" :value="false"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="userList" border style="width: 100%">
      <el-table-column prop="userId" label="用户ID"></el-table-column>
      <el-table-column prop="userName" label="用户名"></el-table-column>
      <el-table-column prop="avatar" label="用户头像" width="110">
        <template #default="{ row }">
          <el-image
            style="width: 50px; height: 50px; border-radius: 50%"
            :src="row.avatar"
            fit="cover"
          >
            <template #error>
              <img
                src="@/assets/app-mj.png"
                alt="avatar"
                style="width: 50px; height: 50px; border-radius: 50%"
              />
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="userType" label="用户类型" width="100">
        <template #default="{ row }">
          {{ row.userType === 1 ? "买家" : "卖家" }}
        </template>
      </el-table-column>
      <el-table-column prop="online" label="在线状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.online ? 'success' : 'info'">
            {{ row.online ? "在线" : "离线" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间">
        <template #default="{ row }">
          {{ new Date(row.createTime).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最后活跃时间">
        <template #default="{ row }">
          {{ new Date(row.updateTime).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" @click="handleViewMessage(row)"> 沟通列表 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryForm.page"
        v-model:page-size="queryForm.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        background
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <!-- 沟通列表 -->
  <el-dialog v-model="chatListDialogShow" title="沟通列表" width="900px" top="100px">
    <chat-list-table
      ref="chatListRef"
      :user-id="currentUserId"
      @view-detail="msgDetail"
    />
  </el-dialog>

  <!-- 查看消息弹窗 -->
  <el-drawer
    class="chat-drawer"
    title="聊天记录"
    v-if="chatDrawerShow"
    v-model="chatDrawerShow"
    direction="rtl"
    size="600px"
    :before-close="handleClose"
  >
    <chat-msg-view
      ref="chatMessagesRef"
      :chat="{
        from: currentUser,
        to: currentToUser,
      }"
      :currentUserId="currentUserId"
      @scroll="handleMessageScroll"
    />
  </el-drawer>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { queryUserList } from "@/api/user";
import { ElMessage } from "element-plus";
import ChatMsgView from "@/components/ChatMsgView.vue";
import ChatListTable from "@/components/ChatListTable.vue";

const loading = ref(false);
const userList = ref([]);
const total = ref(0);

const queryForm = ref({
  userName: "",
  userId: "",
  online: "",
  page: 1,
  pageSize: 10,
});

const getList = async () => {
  loading.value = true;
  try {
    // 过滤查询字段，无值或空值的时候不传该字段
    const queryParams = Object.fromEntries(
      Object.entries(queryForm.value).filter(([_, v]) => v !== "")
    );
    const res = await queryUserList(queryParams);
    userList.value = res.list;
    total.value = res.total;
  } catch (error) {
    console.error(error);
    ElMessage.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryForm.value.page = 1;
  getList();
};

const resetQuery = () => {
  queryForm.value.userName = "";
  queryForm.value.userId = "";
  queryForm.value.online = "";
  queryForm.value.page = 1;
  getList();
};

const handleSizeChange = (val) => {
  queryForm.value.pageSize = val;
  getList();
};

const handleCurrentChange = (val) => {
  queryForm.value.page = val;
  getList();
};

onMounted(() => {
  getList();
});

// 弹窗相关
const chatDrawerShow = ref(false);
const chatListDialogShow = ref(false);
const chatListRef = ref(null);
const chatMessagesRef = ref(null);
const currentUserId = ref("");
const currentUser = ref(""); // 当前用户ID
const currentToUser = ref(""); // 当前接收者ID

// 查看沟通列表
const handleViewMessage = (row) => {
  currentUserId.value = row._id;
  chatListDialogShow.value = true;
};

// 查看消息详情
const msgDetail = async (row) => {
  currentUser.value = row.lastMessage.from;
  currentToUser.value = row.lastMessage.to;
  chatDrawerShow.value = true;
};

const handleClose = () => {
  chatDrawerShow.value = false;
};

const handleMessageScroll = ({ scrollTop }) => {
  // 可以在这里处理额外的滚动事件逻辑
};
</script>

<style scoped>
.query-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  border: 1px solid #e6e6e6;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

<style>
.chat-drawer .el-drawer__header {
  border-bottom: 1px solid #e6e6e6;
  padding-bottom: 20px;
  margin-bottom: 0;
}
.chat-drawer .el-drawer__body {
  padding: 10px;
  display: flex;
  flex-direction: column;
}
</style>
